/**
 * @description 组合概览个基列表
 * @author muisuidaan
 */
import React, { useEffect, useState } from "react";

import { Tabs, Spin } from "antd";
import FundCard from "@/pages/PortfolioOverview/components/FundCard";
import EventEmpty from "@/components/FOF/EventEmpty";

import cn from "classnames";

import {
  getPositionFundInfoClassify,
  getPositionFundInfoList,
} from "./../../portfolio";
import { getUrlParam,listenScroll } from "@/utils/utils";

import styles from "./index.less";



const { TabPane } = Tabs;

const list = [];

const tabs = [
  { fundTypeCode: "all", key: "all", fundTypeName: "全部持仓", ratio: null },
];
interface Props {
  eventCode?: string; //事件code
  id?: string; //跳转的事件id
  innerCode?: string; //跳转的基金innerCode
  time?: string | number; // 重复点击一个内容时用这个来触发
  onDeleteTime:()=>void;
  createBy?:number;//创建人的userId
}
const FundList = (props: Props) => {
  const {  eventCode, innerCode, id, time,onDeleteTime ,createBy} = props;
  const [activeKey, setActiveKey] = useState("all");
  const [topTabs, setTopTabs] = useState([...tabs]); //tab选项

  const [fundList, setFundList] = useState([...list]); //全部的持仓基金列表
  const [showList, setShowList] = useState([...list]); //展示的基金列表
  const [loading, setLoading] = useState(false);

  const [canSetRemark, setCanSetRemark] = useState(false);


  useEffect(()=>{
    if(!createBy)return;
    const authority = localStorage.getItem(`dh-authority`);
    try {
      const userId = JSON.parse(authority)?.userInfo?.userId;
       if(userId == createBy){
        setCanSetRemark(true);
       }else{
        setCanSetRemark(false);
       }
    } catch (error) {
      console.log(error)
    }

  },[createBy])

  //当点击了具体的单基时间列表后跳转
  useEffect(() => {
    if (innerCode && id && time) {
      fundList?.length>0&&setLoading(true);
      handleChangeTab("all");
      //打开对应的基金列表
      setShowList(
        fundList.map((item: any) => {
          // console.log('item.innerCode',item.innerCode,innerCode)
          if (item.innerCode == innerCode) {
            return {
              ...item,
              open: true,
            };
          }
          return item;
        })
      );
      // console.log('innerCode,id',innerCode,id)
    }
  }, [innerCode, id, time]);

  const changeLoadState=(state:boolean)=>{
    if(state){setLoading(false)}
  }
  
  useEffect(()=>{
    if(showList?.length){
      
      const dom = document.getElementById("fund_scroll_container");
      
      listenScroll(dom);
    }
  },[showList])

  useEffect(() => {
    const params = {
      portfolioCode: getUrlParam("id"),
      // "portfolioCode": "DH_HJXFOF006"//todo待修改
    };
    
    getFundList(params); //获取基金列表
  }, []);

  const getFundList = async (params: any) => {
    setLoading(true);
    const res2: any = await getPositionFundInfoClassify(params);
    if (res2?.code === "0") {
      if (res2?.data?.length > 0) {
        setTopTabs([...tabs].concat(res2.data));
      } else {
        setTopTabs([...tabs]);
      }
    }
    const res1: any = await getPositionFundInfoList(params);
    if (res1?.code === "0") {
      if (res1?.data?.length > 0) {
        setFundList(res1.data);
        setShowList(res1.data);
      } else {
        setFundList([]);
      }
    }
   
    setLoading(false);
  };
  

  const handleChangeTab = (key: string) => {
    setActiveKey(key);
    // console.log('key',key,key === "all")
    if (key === "all") {
      setShowList(fundList);
    } else {
      setShowList(fundList.filter((item: any) => item.fundTypeCode === key));
    }
  };

  const onChangeCardState = (info: any) => {
    const copyList = showList.map((item: any) => {
      if (item.innerCode === info.innerCode) {
        return {
          ...item,
          open: !item.open,
        };
      }
      return item;
    });
    setShowList(copyList);
  };

  const renderTab = (key: string) => {
    return (
      <div className="render-list">
        <Spin spinning={loading} >
          <div id="fund_scroll_container" className="scroll-hidden">
            {showList?.length > 0 ? (
              showList.map((item: any,index) => (
                <FundCard
                  active={item.open} //控制基金下的哪个事件列表打开
                  info={{...item,activeKey:key,remarkText:item.remark}}
                  key={item.fundTypeCode+item.secuCode}
                  changeCardState={onChangeCardState}
                  outInnerCode={innerCode}
                  outId={id}
                  outEventCode={eventCode}
                  time={time}
                  changeLoadState={changeLoadState}
                  deleteTime={onDeleteTime}
                  canSetRemark={canSetRemark}
                ></FundCard>
              ))
            ) : (
              <div className={styles.list_no_data_container}><EventEmpty title="暂无数据"></EventEmpty></div>
            )}

          </div>
          
        </Spin>
      </div>
    );
  };

  

  return (
    <div className={cn(styles.fund_list_wrapper)}>
      
      <Tabs
        onChange={handleChangeTab}
        activeKey={activeKey}
        // popupClassName="hhhh"//4.21才支持
      >
        {topTabs.map((item) => (
          <TabPane
            tab={
              // item.fundTypeName
              <p>
                {item?.fundTypeName || "-"}
                {(item?.ratio || item.ratio === 0) && <em>({item?.ratio})</em>}
              </p>
            }
            key={item?.fundTypeCode}
          >
            {(item?.fundTypeCode===activeKey)&&renderTab(activeKey)}
          </TabPane>
        ))}
      </Tabs>
    </div>
  );
};

export default FundList;
